#include "widget.h"

#include "ui_widget.h"
#include <QScreen>
#include <QString>
#include <QPixmap>
#include <QDebug>
#include <QProcess>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    network_assistant = new NetworkAssistant(this);
    network_assistant->hide();

    // QList <QScreen *> list_screen =  QGuiApplication::screens();
    // /* 重设大小 */
    // this->resize(list_screen.at(0)->geometry().width(),
    //              list_screen.at(0)->geometry().height());

    // 设置背景图片
    QPixmap pixmap("../res/bg.png");

    ui->background->setPixmap(pixmap.scaled(1080,720));

    // 设置窗口样式
    ui->widget->setStyleSheet("QWidget#widget{background-color:rgba(255,255,255,0.6);border-radius:20px;}");
        
    // 设置窗口透明度
    this->setWindowOpacity(0.96);

    // 设置窗口标题
    this->setWindowTitle("主界面");

    ui->label->setText("RISC-V车联网盲区检测系统");

     /* 信号槽连接 */
    connect(ui->pushButton, SIGNAL(clicked()),
            this, SLOT(startNetworkAssistant()));
    connect(ui->pushButton_2, SIGNAL(clicked()),
            this, SLOT(sendImage()));
    connect(ui->pushButton_3, SIGNAL(clicked()),
            this, SLOT(receiveImage()));

    image_cam.init();  //初始化
    connect(&image_cam,SIGNAL(sendReceiveImageToWidget(const QImage &)), this, SLOT(showImage(const QImage &)));
    connect(&receive_image, SIGNAL(sendReceiveImageToWidget(const QImage &)), this, SLOT(showReceiveCamera(const QImage &)));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::startNetworkAssistant()
{
    this->hide();
    network_assistant->show();
}

void Widget::receiveImage()
{
    if ( !receive_image.init())
    {
        QMessageBox::warning(nullptr, "失败", "接收图片失败！请检查你的网络！", QMessageBox::Yes, QMessageBox::Yes);
        this->close();
    }
    connect(receive_image.receiver,SIGNAL(readyRead()),&receive_image,SLOT(receiveVideo()));
}

void Widget::sendImage()
{
    // // 创建一个 QProcess 对象
    // QProcess process;

    // // 设置要执行的命令和参数
    // QString program = "sudo";
    // QStringList arguments;
    // arguments << "./yolov5n/yolov5n"<<"yolov5n/hhb_out/hhb.bm"<<"/dev/video0";

    // // 启动命令
    // process.start(program, arguments);
    // process.waitForFinished();

    // // 检查命令执行结果
    // int exitCode = process.exitCode();
    // if (exitCode == 0) {
    //     qDebug() << "目录创建成功！";
    // } else {
    //     qDebug() << "目录创建失败，错误码：" << exitCode;
    // }

    // system("./yolov5n/yolov5n yolov5n/hhb_out/hhb.bm /dev/video0");
    
    connect(image_cam.udpSocket_recv,SIGNAL(readyRead()),&image_cam,SLOT(receiveYolov5Image()));
    image_cam.start();
}

void Widget::showImage(const QImage &image)
{
    QPixmap pix = QPixmap::fromImage(image).scaled(ui->label_9->size());
    ui->label_7->setPixmap(pix);
}

//显示接收端的画面
void Widget::showReceiveCamera(const QImage &image)
{
    //  显示接收到的图片数据
    QPixmap pix = QPixmap::fromImage(image).scaled(ui->label_9->size());
    ui->label_9->setPixmap(pix);
}